<?php


namespace app\admin\services;


use app\admin\exception\ModelNotFoundException;
use app\common\caches\GameCache;
use app\common\models\Game;
use app\Request;

class GameService
{
    private $gameModel;

    public function __construct(Game $gameModel)
    {
        $this->gameModel = $gameModel;
    }

    public function index(Request $request)
    {
        $name = $request->get('name', '');
        if (!empty($name)){
            $this->gameModel = $this->gameModel->where('name', '=', $name);
        }
        $limit = $request->get('limit', 10);
        $page = $request->get('page', 1);
        return $this->gameModel->order('id')->paginate([
            'list_rows' => $limit,
            'page' => $page
        ]);
    }

    public function create(Request $request)
    {
        $data = $request->post(['name', 'icon', 'platform', 'access_ips']);
        $game = $this->gameModel->createRow($data);
        GameCache::setGameByAppId($game->app_id, $game);
        return $game;
    }

    public function update(Request $request, $id)
    {
        $game = $this->gameModel->where('id', '=', $id)->find();
        if (!$game){
            throw new ModelNotFoundException('不存在该游戏');
        }
        $data = $request->put(['name', 'icon', 'platform', 'access_ips']);
        $game->save($data);
        GameCache::setGameByAppId($game->app_id, $game);
        return true;
    }

    public function delete($id)
    {
        $game = $this->gameModel->where('id', '=', $id)->find();
        if (!$game){
            throw new ModelNotFoundException('不存在该游戏');
        }
        GameCache::delGameByAppId($game->app_id);
        return $game->delete();
    }

    public function show($id)
    {
        return $this->gameModel->find($id);
    }

    public function cache()
    {
        $games = $this->gameModel->select();
        if ($games->isEmpty()) return true;
        foreach ($games as $game){
            GameCache::setGameByAppId($game->app_id, $game);
        }
        return true;
    }
}
